package com.example.withroadlogistics.MyTask;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import com.example.withroadlogistics.Adapter.Adapter_Clock;
import com.example.withroadlogistics.Adapter.Adapter_VTaskRoute;
import com.example.withroadlogistics.R;
import com.example.withroadlogistics.model.Clock;
import com.example.withroadlogistics.model.VTaskRroute;
import com.example.withroadlogistics.until.HttpCallbackListener;
import com.example.withroadlogistics.until.HttpUtil;
import com.example.withroadlogistics.until.MySharedPreferences;
import com.example.withroadlogistics.until.constant;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class Mytransport extends AppCompatActivity {
    private ListView mListView;
    private List<VTaskRroute> mList = new ArrayList<>();

    //获取路线打码点
    private ListView mListView1;
    private List<Clock> mList1 = new ArrayList<>();

    private String TAG = "ifu25";
    private String originAddress = constant.url+ "route/getCurrentByUserId";
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String result = "";

            if ("OK".equals(msg.obj.toString())){
                result = "success";
            }else if ("Wrong".equals(msg.obj.toString())){
                result = "fail";
            }else {
                String data = msg.obj.toString();
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    String code = jsonObject.getString("code");
                    if (code.equals("0")) {
                        result = jsonObject.getString("data");
                       // Toast.makeText(Mytransport.this, result, Toast.LENGTH_LONG).show();
                        Toast.makeText(Mytransport.this, "获取相关内容成功！", Toast.LENGTH_LONG).show();
                        try {
                            JSONArray jsonList = jsonObject.getJSONArray("data");
                            for(int i=0;i<jsonList.length();i++){
                                Log.i(TAG, "handleMessage: "+jsonList);
                                JSONObject json = jsonList.getJSONObject(i);
                                String taskId=json.getString("taskId");
                                String userId=json.getString("userId");
                                String carId=json.getString("carId");
                                boolean taskIsdit= json.getBoolean("taskIsdit");
                                String createDate=json.getString("createDate");
                                String state=json.getString("state");
                                /*String taskRemark=json.getString("taskRemark");*/
                                int routeId=Integer.parseInt(json.getString("routeId"));
                                String routeName=json.getString("routeName");
                                String stateTime=json.getString("stateTime");
                                String endTime=json.getString("endTime");
                                String endIsdit=json.getString("endIsdit");
                                /*String routeRemark=json.getString("routeRemark");*/
                                String start=json.getString("start");
                                String realName=json.getString("realName");
                                String ends=json.getString("ends");
                                // String routenote=json.getString("routenote");
                                mList.add(new VTaskRroute(taskId,userId,carId,taskIsdit,createDate,state,routeId,routeName,stateTime,endTime,endIsdit,start,realName,ends));
                                Adapter_VTaskRoute adapter = new Adapter_VTaskRoute(Mytransport.this,mList);
                                MySharedPreferences.setRouteId(String.valueOf(routeId), Mytransport.this);
                                mListView.setAdapter(adapter);
                                // finish();一闪而过
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(Mytransport.this, "网路异常，请退出登陆重试！", Toast.LENGTH_LONG).show();
                        }


                    }else {
                        result = jsonObject.getString("data");
                       // Toast.makeText(Mytransport.this, result, Toast.LENGTH_LONG).show();
                        Toast.makeText(Mytransport.this, "获取相关内容失败！", Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Toast.makeText(Mytransport.this, "获取相关内容异常！", Toast.LENGTH_LONG).show();
                }

            }

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sendeUserId();
        setContentView(R.layout.activity_mytransport);
        mListView =findViewById(R.id.mListView);
        mListView1 =findViewById(R.id.dakamListView);
    }

    private boolean isInputValid() {
        //检查用户输入的合法性，这里暂且默认用户输入合法
        return true;
    }

    public void sendeUserId() {
        //取得用户输入的账号和密码
        if (!isInputValid()){
            return;
        }
        String userId = (String) MySharedPreferences.getUserId(Mytransport.this);
        if (userId.isEmpty()) {
            Toast.makeText(Mytransport.this, "用户失效请重新登陆！", Toast.LENGTH_LONG).show();
            return;
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put(VTaskRroute.USERID, userId);
        try {
            String compeletedURL = HttpUtil.getURLWithParams(originAddress, params);
            HttpUtil.sendHttpRequest(compeletedURL, new HttpCallbackListener() {
                @Override
                public void onFinish(String response) {
                    Message message = new Message();
                    message.obj = response;
                    mHandler.sendMessage(message);
                }

                @Override
                public void onError(Exception e) {
                    Message message = new Message();
                    message.obj = e.toString();
                    mHandler.sendMessage(message);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onWindowFocusChanged(boolean hasFocus)
    {
        /**
         * 请求数据
         * 解析json
         * 适配器
         * 绑值显示
         */
        if (hasFocus){
            //访问本地接口，用10.0.2.2取代localhost
            String userId = (String) MySharedPreferences.getUserId(Mytransport.this);
            String routeId = (String) MySharedPreferences.getRouteid(Mytransport.this);
            String page="1";
            String limit="5";
            final String url = constant.url+"clock/getClockALL?routeId="+routeId+"&page="+page+"&limit="+limit;

            RxVolley.get(url, new HttpCallback() {
                @Override
                public void onSuccess(String t) {
                   Toast.makeText(Mytransport.this,t,Toast.LENGTH_LONG).show();
                    //控制台输出Json
                     Log.d("aaaa",""+t);
                    //解析json
                    parsingJson(t);

                    Adapter_Clock adapter1 = new Adapter_Clock(Mytransport.this,mList1);

                    //mListView1.setAdapter(adapter1);
                    Log.i(TAG, "parsingJson: "+url);
                }
            });
        }
    }

    //数据解析
    public void parsingJson(String t){
        try {

            JSONObject jsonObject = new JSONObject(t);
            JSONArray jsonList = jsonObject.getJSONArray("data");
            for(int i=0;i<jsonList.length();i++){
                JSONObject json = jsonList.getJSONObject(i);
                int clockId=Integer.parseInt(json.getString("clockId"));
                int routeId=Integer.parseInt(json.getString("routeId"));
                boolean isClock=json.getBoolean("isClock");
                String clockTime=json.getString("clockTime");
                int qrcodeId=Integer.parseInt(json.getString("qrcodeId"));
                String clockContent=json.getString("clockContent");
                String clockRemark=json.getString("clockRemark");

                //要将model定义的成员全部写出
                mList1.add(new Clock(clockId,routeId,isClock,clockTime,qrcodeId,clockContent,clockRemark));
                Adapter_Clock adapter1 = new Adapter_Clock(Mytransport.this,mList1);
               // mListView1.setAdapter(adapter1);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}
